// key-value 模型
public class HashBuck {
    private static class Node {
        private int key;
        private int val;
        Node next;


        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;//负载因子

    public HashBuck() {
        this.array = new Node[10];
    }

    public void put(int key, int val) {
        //计算哈希值得到索引
        int index = key % array.length;
        Node cur = array[index];

        if(cur == null){
            array[index] = new Node(key,val);
            size++;
            if(loadFactor() > LOAD_FACTOR){
                resize();
            }
            return;
        }

        //找末尾节点
        while(cur != null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            if(cur.next == null){
                break;
            }
            cur = cur.next;
        }

        cur.next = new Node(key,val);
        size++;

        if(loadFactor() > LOAD_FACTOR){
            resize();
        }

    }


    private void resize() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                Node curN = cur.next;
                int newIndex = cur.key % newArray.length;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
